home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / epsilon / extime.py < prev    next >
Text File  |  2009-03-13  |  36KB  |  949 lines

  1. # -*- test-case-name: epsilon.test.test_extime -*-
  2. """
  3. Extended date/time formatting and miscellaneous functionality.
  4.  
  5. See the class 'Time' for details.
  6. """
  7.  
  8. import datetime
  9. import re
  10.  
  11. from email.Utils import parsedate_tz
  12.  
  13. _EPOCH = datetime.datetime.utcfromtimestamp(0)
  14.  
  15. def sanitizeStructTime(struct):
  16.     """
  17.     Convert struct_time tuples with possibly invalid values to valid
  18.     ones by substituting the closest valid value.
  19.     """
  20.     maxValues = (9999, 12, 31, 23, 59, 59)
  21.     minValues = (1, 1, 1, 0, 0, 0)
  22.     newstruct = []
  23.     for value, maxValue, minValue in zip(struct[:6], maxValues, minValues):
  24.         newstruct.append(max(minValue, min(value, maxValue)))
  25.     return tuple(newstruct) + struct[6:]
  26.  
  27. def _timedeltaToSignHrMin(offset):
  28.     """
  29.     Return a (sign, hour, minute) triple for the offset described by timedelta.
  30.  
  31.     sign is a string, either "+" or "-". In the case of 0 offset, sign is "+".
  32.     """
  33.     minutes = round((offset.days * 3600000000 * 24
  34.                      + offset.seconds * 1000000
  35.                      + offset.microseconds)
  36.                     / 60000000.0)
  37.     if minutes < 0:
  38.         sign = '-'
  39.         minutes = -minutes
  40.     else:
  41.         sign = '+'
  42.     return (sign, minutes // 60, minutes % 60)
  43.  
  44. def _timedeltaToSeconds(offset):
  45.     """
  46.     Convert a datetime.timedelta instance to simply a number of seconds.
  47.  
  48.     For example, you can specify purely second intervals with timedelta's
  49.     constructor:
  50.  
  51.         >>> td = datetime.timedelta(seconds=99999999)
  52.  
  53.     but then you can't get them out again:
  54.  
  55.         >>> td.seconds
  56.         35199
  57.  
  58.     This allows you to:
  59.  
  60.         >>> import epsilon.extime
  61.         >>> epsilon.extime._timedeltaToSeconds(td)
  62.         99999999.0
  63.  
  64.     @param offset: a L{datetime.timedelta} representing an interval that we
  65.     wish to know the total number of seconds for.
  66.  
  67.     @return: a number of seconds
  68.     @rtype: float
  69.     """
  70.     return ((offset.days * 60*60*24) +
  71.             (offset.seconds) +
  72.             (offset.microseconds * 1e-6))
  73.  
  74. class FixedOffset(datetime.tzinfo):
  75.     _zeroOffset = datetime.timedelta()
  76.  
  77.     def __init__(self, hours, minutes):
  78.         self.offset = datetime.timedelta(minutes = hours * 60 + minutes)
  79.  
  80.     def utcoffset(self, dt):
  81.         return self.offset
  82.  
  83.     def tzname(self, dt):
  84.         return _timedeltaToSignHrMin(self.offset)
  85.  
  86.     def dst(self, tz):
  87.         return self._zeroOffset
  88.  
  89.     def __repr__(self):
  90.         return '<%s.%s object at 0x%x offset %r>' % (
  91.             self.__module__, type(self).__name__, id(self), self.offset)
  92.  
  93.  
  94.  
  95. class Time(object):
  96.     """An object representing a well defined instant in time.
  97.  
  98.     A Time object unambiguously addresses some time, independent of timezones,
  99.     contorted base-60 counting schemes, leap seconds, and the effects of
  100.     general relativity. It provides methods for returning a representation of
  101.     this time in various ways that a human or a programmer might find more
  102.     useful in various applications.
  103.  
  104.     Every Time instance has an attribute 'resolution'. This can be ignored, or
  105.     the instance can be considered to address a span of time. This resolution
  106.     is determined by the value used to initalize the instance, or the
  107.     resolution of the internal representation, whichever is greater. It is
  108.     mostly useful when using input formats that allow the specification of
  109.     whole days or weeks. For example, ISO 8601 allows one to state a time as,
  110.     "2005-W03", meaning "the third week of 2005". In this case the resolution
  111.     is set to one week. Other formats are considered to express only an instant
  112.     in time, such as a POSIX timestamp, because the resolution of the time is
  113.     limited only by the hardware's representation of a real number.
  114.  
  115.     Timezones are significant only for instances with a resolution greater than
  116.     one day. When the timezone is insignificant, the result of methods like
  117.     asISO8601TimeAndDate is the same for any given tzinfo parameter. Sort order
  118.     is determined by the start of the period in UTC. For example, "today" sorts
  119.     after "midnight today, central Europe", and before "midnight today, US
  120.     Eastern". For applications that need to store a mix of timezone dependent
  121.     and independent instances, it may be wise to store them separately, since
  122.     the time between the start and end of today in the local timezone may not
  123.     include the start of today in UTC, and thus not independent instances
  124.     addressing the whole day. In other words, the desired sort order (the one
  125.     where just "Monday" sorts before any more precise time in "Monday", and
  126.     after any in "Sunday") of Time instances is dependant on the timezone
  127.     context.
  128.  
  129.     Date arithmetic and boolean operations operate on instants in time, not
  130.     periods. In this case, the start of the period is used as the value, and
  131.     the result has a resolution of 0.
  132.  
  133.     For containment tests with the 'in' operator, the period addressed by the
  134.     instance is used.
  135.  
  136.     The methods beginning with 'from' are constructors to create instances from
  137.     various formats. Some of them are textual formats, and others are other
  138.     time types commonly found in Python code.
  139.  
  140.     Likewise, methods beginning with 'as' return the represented time in
  141.     various formats. Some of these methods should try to reflect the resolution
  142.     of the instance. However, they don't yet.
  143.  
  144.     For formats with both a constructor and a formatter, d == fromFu(d.asFu())
  145.  
  146.     @type resolution: datetime.timedelta
  147.     @ivar resolution: the length of the period to which this instance could
  148.     refer. For example, "Today, 13:38" could refer to any time between 13:38
  149.     until but not including 13:39. In this case resolution would be
  150.     timedelta(minutes=1).
  151.     """
  152.  
  153.     # the instance variable _time is the internal representation of time. It
  154.     # is a naive datetime object which is always UTC. A UTC tzinfo would be
  155.     # great, if one existed, and anyway it complicates pickling.
  156.  
  157.     rfc2822Weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  158.  
  159.     rfc2822Months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
  160.                      'Sep', 'Oct', 'Nov', 'Dec']
  161.  
  162.     resolution = datetime.timedelta.resolution
  163.  
  164.     #
  165.     # Methods to create new instances
  166.     #
  167.  
  168.     def __init__(self):
  169.         """Return a new Time instance representing the time now.
  170.  
  171.         See also the fromFu methods to create new instances from other types of
  172.         initializers.
  173.         """
  174.         self._time = datetime.datetime.utcnow()
  175.  
  176.  
  177.     def _fromWeekday(klass, match, tzinfo, now):
  178.         weekday = klass.weekdays.index(match.group('weekday').lower())
  179.         dtnow = now.asDatetime().replace(
  180.             hour=0, minute=0, second=0, microsecond=0)
  181.         daysInFuture = (weekday - dtnow.weekday()) % len(klass.weekdays)
  182.         if daysInFuture == 0:
  183.             daysInFuture = 7
  184.         self = klass.fromDatetime(dtnow + datetime.timedelta(days=daysInFuture))
  185.         assert self.asDatetime().weekday() == weekday
  186.         self.resolution = datetime.timedelta(days=1)
  187.         return self
  188.  
  189.  
  190.     def _fromTodayOrTomorrow(klass, match, tzinfo, now):
  191.         dtnow = now.asDatetime().replace(
  192.             hour=0, minute=0, second=0, microsecond=0)
  193.         when = match.group(0).lower()
  194.         if when == 'tomorrow':
  195.             dtnow += datetime.timedelta(days=1)
  196.         elif when == 'yesterday':
  197.             dtnow -= datetime.timedelta(days=1)
  198.         else:
  199.             assert when == 'today'
  200.         self = klass.fromDatetime(dtnow)
  201.         self.resolution = datetime.timedelta(days=1)
  202.         return self
  203.  
  204.  
  205.     def _fromTime(klass, match, tzinfo, now):
  206.         minute = int(match.group('minute'))
  207.         hour = int(match.group('hour'))
  208.         ampm = (match.group('ampm') or '').lower()
  209.         if ampm:
  210.             if not 1 <= hour <= 12:
  211.                 raise ValueError, 'hour %i is not in 1..12' % (hour,)
  212.             if hour == 12 and ampm == 'am':
  213.                 hour = 0
  214.             elif ampm == 'pm':
  215.                 hour += 12
  216.         if not 0 <= hour <= 23:
  217.             raise ValueError, 'hour %i is not in 0..23' % (hour,)
  218.  
  219.         dtnow = now.asDatetime(tzinfo).replace(second=0, microsecond=0)
  220.         dtthen = dtnow.replace(hour=hour, minute=minute)
  221.         if dtthen < dtnow:
  222.             dtthen += datetime.timedelta(days=1)
  223.  
  224.         self = klass.fromDatetime(dtthen)
  225.         self.resolution = datetime.timedelta(minutes=1)
  226.         return self
  227.  
  228.  
  229.     def _fromNoonOrMidnight(klass, match, tzinfo, now):
  230.         when = match.group(0).lower()
  231.         if when == 'noon':
  232.             hour = 12
  233.         else:
  234.             assert when == 'midnight'
  235.             hour = 0
  236.         dtnow = now.asDatetime(tzinfo).replace(
  237.             minute=0, second=0, microsecond=0)
  238.         dtthen = dtnow.replace(hour=hour)
  239.         if dtthen < dtnow:
  240.             dtthen += datetime.timedelta(days=1)
  241.  
  242.         self = klass.fromDatetime(dtthen)
  243.         self.resolution = datetime.timedelta(minutes=1)
  244.         return self
  245.  
  246.     def _fromNow(klass, match, tzinfo, now):
  247.         # coerce our 'now' argument to an instant
  248.         return now + datetime.timedelta(0)
  249.  
  250.     weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
  251.                 'saturday', 'sunday']
  252.  
  253.     humanlyPatterns = [
  254.         (re.compile(r"""
  255.             \b
  256.             ((next|this)\s+)?
  257.             (?P<weekday>
  258.                 monday
  259.                 | tuesday
  260.                 | wednesday
  261.                 | thursday
  262.                 | friday
  263.                 | saturday
  264.                 | sunday
  265.             )
  266.             \b
  267.             """, re.IGNORECASE | re.VERBOSE),
  268.             _fromWeekday),
  269.         (re.compile(r"\b(today|tomorrow|yesterday)\b", re.IGNORECASE),
  270.             _fromTodayOrTomorrow),
  271.         (re.compile(r"""
  272.             \b
  273.             (?P<hour>\d{1,2}):(?P<minute>\d{2})
  274.             (\s*(?P<ampm>am|pm))?
  275.             \b
  276.             """, re.IGNORECASE | re.VERBOSE),
  277.             _fromTime),
  278.         (re.compile(r"\b(noon|midnight)\b", re.IGNORECASE),
  279.             _fromNoonOrMidnight),
  280.         (re.compile(r"\b(now)\b", re.IGNORECASE),
  281.             _fromNow),
  282.     ]
  283.  
  284.     _fromWeekday = classmethod(_fromWeekday)
  285.     _fromTodayOrTomorrow = classmethod(_fromTodayOrTomorrow)
  286.     _fromTime = classmethod(_fromTime)
  287.     _fromNoonOrMidnight = classmethod(_fromNoonOrMidnight)
  288.     _fromNow = classmethod(_fromNow)
  289.  
  290.  
  291.     def fromHumanly(klass, humanStr, tzinfo=None, now=None):
  292.         """Return a new Time instance from a string a human might type.
  293.  
  294.         @param humanStr: the string to be parsed.
  295.  
  296.         @param tzinfo: A tzinfo instance indicating the timezone to assume if
  297.         none is specified in humanStr. If None, assume UTC.
  298.  
  299.         @param now: A Time instance to be considered "now" for when
  300.         interpreting relative dates like "tomorrow". If None, use the real now.
  301.  
  302.         Total crap now, it just supports weekdays, "today" and "tomorrow" for
  303.         now. This is pretty insufficient and useless, but good enough for some
  304.         demo functionality, or something.
  305.         """
  306.         humanStr = humanStr.strip()
  307.         if now is None:
  308.             now = Time()
  309.         if tzinfo is None:
  310.             tzinfo = FixedOffset(0, 0)
  311.  
  312.         for pattern, creator in klass.humanlyPatterns:
  313.             match = pattern.match(humanStr)
  314.             if not match \
  315.             or match.span()[1] != len(humanStr):
  316.                 continue
  317.             try:
  318.                 return creator(klass, match, tzinfo, now)
  319.             except ValueError:
  320.                 continue
  321.         raise ValueError, 'could not parse date: %r' % (humanStr,)
  322.  
  323.     fromHumanly = classmethod(fromHumanly)
  324.  
  325.  
  326.     iso8601pattern = re.compile(r"""
  327.         ^ (?P<year> \d{4})
  328.         (
  329.             # a year may optionally be followed by one of:
  330.             # - a month
  331.             # - a week
  332.             # - a specific day, and an optional time
  333.             #     a specific day is one of:
  334.             #     - a month and day
  335.             #     - week and weekday
  336.             #     - a day of the year
  337.             (
  338.                 -? (?P<month1> \d{2})
  339.                 |
  340.                 -? W (?P<week1> \d{2})
  341.                 |
  342.                 (
  343.                     -? (?P<month2> \d{2})
  344.                     -? (?P<day> \d{2})
  345.                     |
  346.                     -? W (?P<week2> \d{2})
  347.                     -? (?P<weekday> \d)
  348.                     |
  349.                     -? (?P<dayofyear> \d{3})
  350.                 )
  351.                 (
  352.                     T (?P<hour> \d{2})
  353.                     (
  354.                         :? (?P<minute> \d{2})
  355.                         (
  356.                             :? (?P<second> \d{2})
  357.                             (
  358.                                 [\.,] (?P<fractionalsec> \d+)
  359.                             )?
  360.                         )?
  361.                     )?
  362.                     (
  363.                         (?P<zulu> Z)
  364.                         |
  365.                         (?P<tzhour> [+\-]\d{2})
  366.                         (
  367.                             :? (?P<tzmin> \d{2})
  368.                         )?
  369.                     )?
  370.                 )?
  371.             )?
  372.         )? $""", re.VERBOSE)
  373.  
  374.  
  375.     def fromISO8601TimeAndDate(klass, iso8601string, tzinfo=None):
  376.         """Return a new Time instance from a string formated as in ISO 8601.
  377.  
  378.         If the given string contains no timezone, it is assumed to be in the
  379.         timezone specified by the parameter `tzinfo`, or UTC if tzinfo is None.
  380.         An input string with an explicit timezone will always override tzinfo.
  381.  
  382.         If the given iso8601string does not contain all parts of the time, they
  383.         will default to 0 in the timezone given by `tzinfo`.
  384.  
  385.         WARNING: this function is incomplete. ISO is dumb and their standards
  386.         are not free. Only a subset of all valid ISO 8601 dates are parsed,
  387.         because I can't find a formal description of the format. However,
  388.         common ones should work.
  389.         """
  390.  
  391.         def calculateTimezone():
  392.             if groups['zulu'] == 'Z':
  393.                 return FixedOffset(0, 0)
  394.             else:
  395.                 tzhour = groups.pop('tzhour')
  396.                 tzmin = groups.pop('tzmin')
  397.                 if tzhour is not None:
  398.                     return FixedOffset(int(tzhour), int(tzmin or 0))
  399.             return tzinfo or FixedOffset(0, 0)
  400.  
  401.         def coerceGroups():
  402.             groups['month'] = groups['month1'] or groups['month2']
  403.             groups['week'] = groups['week1'] or groups['week2']
  404.             # don't include fractional seconds, because it's not an integer.
  405.             defaultTo0 = ['hour', 'minute', 'second']
  406.             defaultTo1 = ['month', 'day', 'week', 'weekday', 'dayofyear']
  407.             if groups['fractionalsec'] is None:
  408.                 groups['fractionalsec'] = '0'
  409.             for key in defaultTo0:
  410.                 if groups[key] is None:
  411.                     groups[key] = 0
  412.             for key in defaultTo1:
  413.                 if groups[key] is None:
  414.                     groups[key] = 1
  415.             groups['fractionalsec'] = float('.'+groups['fractionalsec'])
  416.             for key in defaultTo0 + defaultTo1 + ['year']:
  417.                 groups[key] = int(groups[key])
  418.  
  419.             for group, min, max in [
  420.                 # some years have only 52 weeks
  421.                 ('week', 1, 53),
  422.                 ('weekday', 1, 7),
  423.                 ('month', 1, 12),
  424.                 ('day', 1, 31),
  425.                 ('hour', 0, 24),
  426.                 ('minute', 0, 59),
  427.  
  428.                 # Sometime in the 22nd century AD, two leap seconds will be
  429.                 # required every year.  In the 25th century AD, four every
  430.                 # year.  We'll ignore that for now though because it would be
  431.                 # tricky to get right and we certainly don't need it for our
  432.                 # target applications.  In other words, post-singularity
  433.                 # Martian users, please do not rely on this code for
  434.                 # compatibility with Greater Galactic Protectorate of Earth
  435.                 # date/time formatting!  Apologies, but no library I know of in
  436.                 # Python is sufficient for processing their dates and times
  437.                 # without ADA bindings to get the radiation-safety zone counter
  438.                 # correct. -glyph
  439.  
  440.                 ('second', 0, 61),
  441.                 # don't forget leap years
  442.                 ('dayofyear', 1, 366)]:
  443.                 if not min <= groups[group] <= max:
  444.                     raise ValueError, '%s must be in %i..%i' % (group, min, max)
  445.  
  446.         def determineResolution():
  447.             if match.group('fractionalsec') is not None:
  448.                 return max(datetime.timedelta.resolution,
  449.                     datetime.timedelta(
  450.                         microseconds=1 * 10 ** -len(
  451.                             match.group('fractionalsec')) * 1000000))
  452.  
  453.             for testGroup, resolution in [
  454.             ('second', datetime.timedelta(seconds=1)),
  455.             ('minute', datetime.timedelta(minutes=1)),
  456.             ('hour', datetime.timedelta(hours=1)),
  457.             ('weekday', datetime.timedelta(days=1)),
  458.             ('dayofyear', datetime.timedelta(days=1)),
  459.             ('day', datetime.timedelta(days=1)),
  460.             ('week1', datetime.timedelta(weeks=1)),
  461.             ('week2', datetime.timedelta(weeks=1))]:
  462.                 if match.group(testGroup) is not None:
  463.                     return resolution
  464.  
  465.             if match.group('month1') is not None \
  466.             or match.group('month2') is not None:
  467.                 if self._time.month == 12:
  468.                     return datetime.timedelta(days=31)
  469.                 nextMonth = self._time.replace(month=self._time.month+1)
  470.                 return nextMonth - self._time
  471.             else:
  472.                 nextYear = self._time.replace(year=self._time.year+1)
  473.                 return nextYear - self._time
  474.  
  475.         def calculateDtime(tzinfo):
  476.             """Calculate a datetime for the start of the addressed period."""
  477.  
  478.             if match.group('week1') is not None \
  479.             or match.group('week2') is not None:
  480.                 if not 0 < groups['week'] <= 53:
  481.                     raise ValueError(
  482.                         'week must be in 1..53 (was %i)' % (groups['week'],))
  483.                 dtime = datetime.datetime(
  484.                     groups['year'],
  485.                     1,
  486.                     4,
  487.                     groups['hour'],
  488.                     groups['minute'],
  489.                     groups['second'],
  490.                     int(round(groups['fractionalsec'] * 1000000)),
  491.                     tzinfo=tzinfo
  492.                 )
  493.                 dtime -= datetime.timedelta(days = dtime.weekday())
  494.                 dtime += datetime.timedelta(
  495.                     days = (groups['week']-1) * 7 + groups['weekday'] - 1)
  496.                 if dtime.isocalendar() != (
  497.                     groups['year'], groups['week'], groups['weekday']):
  498.                     # actually the problem could be an error in my logic, but
  499.                     # nothing should cause this but requesting week 53 of a
  500.                     # year with 52 weeks.
  501.                     raise ValueError('year %04i has no week %02i' %
  502.                                      (groups['year'], groups['week']))
  503.                 return dtime
  504.  
  505.             if match.group('dayofyear') is not None:
  506.                 dtime = datetime.datetime(
  507.                     groups['year'],
  508.                     1,
  509.                     1,
  510.                     groups['hour'],
  511.                     groups['minute'],
  512.                     groups['second'],
  513.                     int(round(groups['fractionalsec'] * 1000000)),
  514.                     tzinfo=tzinfo
  515.                 )
  516.                 dtime += datetime.timedelta(days=groups['dayofyear']-1)
  517.                 if dtime.year != groups['year']:
  518.                     raise ValueError(
  519.                         'year %04i has no day of year %03i' %
  520.                         (groups['year'], groups['dayofyear']))
  521.                 return dtime
  522.  
  523.             else:
  524.                 return datetime.datetime(
  525.                     groups['year'],
  526.                     groups['month'],
  527.                     groups['day'],
  528.                     groups['hour'],
  529.                     groups['minute'],
  530.                     groups['second'],
  531.                     int(round(groups['fractionalsec'] * 1000000)),
  532.                     tzinfo=tzinfo
  533.                 )
  534.  
  535.  
  536.         match = klass.iso8601pattern.match(iso8601string)
  537.         if match is None:
  538.             raise ValueError(
  539.                 '%r could not be parsed as an ISO 8601 date and time' %
  540.                 (iso8601string,))
  541.  
  542.         groups = match.groupdict()
  543.         coerceGroups()
  544.         if match.group('hour') is not None:
  545.             timezone = calculateTimezone()
  546.         else:
  547.             timezone = None
  548.         self = klass.fromDatetime(calculateDtime(timezone))
  549.         self.resolution = determineResolution()
  550.         return self
  551.  
  552.     fromISO8601TimeAndDate = classmethod(fromISO8601TimeAndDate)
  553.  
  554.     def fromStructTime(klass, structTime, tzinfo=None):
  555.         """Return a new Time instance from a time.struct_time.
  556.  
  557.         If tzinfo is None, structTime is in UTC. Otherwise, tzinfo is a
  558.         datetime.tzinfo instance coresponding to the timezone in which
  559.         structTime is.
  560.  
  561.         Many of the functions in the standard time module return these things.
  562.         This will also work with a plain 9-tuple, for parity with the time
  563.         module. The last three elements, or tm_wday, tm_yday, and tm_isdst are
  564.         ignored.
  565.         """
  566.         dtime = datetime.datetime(tzinfo=tzinfo, *structTime[:6])
  567.         self = klass.fromDatetime(dtime)
  568.         self.resolution = datetime.timedelta(seconds=1)
  569.         return self
  570.  
  571.     fromStructTime = classmethod(fromStructTime)
  572.  
  573.     def fromDatetime(klass, dtime):
  574.         """Return a new Time instance from a datetime.datetime instance.
  575.  
  576.         If the datetime instance does not have an associated timezone, it is
  577.         assumed to be UTC.
  578.         """
  579.         self = klass.__new__(klass)
  580.         if dtime.tzinfo is not None:
  581.             self._time = dtime.astimezone(FixedOffset(0, 0)).replace(tzinfo=None)
  582.         else:
  583.             self._time = dtime
  584.         self.resolution = datetime.timedelta.resolution
  585.         return self
  586.  
  587.     fromDatetime = classmethod(fromDatetime)
  588.  
  589.     def fromPOSIXTimestamp(klass, secs):
  590.         """Return a new Time instance from seconds since the POSIX epoch.
  591.  
  592.         The POSIX epoch is midnight Jan 1, 1970 UTC. According to POSIX, leap
  593.         seconds don't exist, so one UTC day is exactly 86400 seconds, even if
  594.         it wasn't.
  595.  
  596.         @param secs: a number of seconds, represented as an integer, long or
  597.         float.
  598.         """
  599.         self = klass.fromDatetime(_EPOCH + datetime.timedelta(seconds=secs))
  600.         self.resolution = datetime.timedelta()
  601.         return self
  602.  
  603.     fromPOSIXTimestamp = classmethod(fromPOSIXTimestamp)
  604.  
  605.     def fromRFC2822(klass, rfc822string):
  606.         """
  607.         Return a new Time instance from a string formated as described in RFC 2822.
  608.  
  609.         @type rfc822string: str
  610.  
  611.         @raise ValueError: if the timestamp is not formatted properly (or if
  612.         certain obsoleted elements of the specification are used).
  613.  
  614.         @return: a new L{Time}
  615.         """
  616.  
  617.         # parsedate_tz is going to give us a "struct_time plus", a 10-tuple
  618.         # containing the 9 values a struct_time would, i.e.: (tm_year, tm_mon,
  619.         # tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst), plus a
  620.         # bonus "offset", which is an offset (in _seconds_, of all things).
  621.  
  622.         maybeStructTimePlus = parsedate_tz(rfc822string)
  623.  
  624.         if maybeStructTimePlus is None:
  625.             raise ValueError, 'could not parse RFC 2822 date %r' % (rfc822string,)
  626.         structTimePlus = sanitizeStructTime(maybeStructTimePlus)
  627.         offsetInSeconds = structTimePlus[-1]
  628.         if offsetInSeconds is None:
  629.             offsetInSeconds = 0
  630.         self = klass.fromStructTime(
  631.             structTimePlus,
  632.             FixedOffset(
  633.                 hours=0,
  634.                 minutes=offsetInSeconds // 60))
  635.         self.resolution = datetime.timedelta(seconds=1)
  636.         return self
  637.  
  638.     fromRFC2822 = classmethod(fromRFC2822)
  639.  
  640.     #
  641.     # Methods to produce various formats
  642.     #
  643.  
  644.     def asPOSIXTimestamp(self):
  645.         """Return this time as a timestamp as specified by POSIX.
  646.  
  647.         This timestamp is the count of the number of seconds since Midnight,
  648.         Jan 1 1970 UTC, ignoring leap seconds.
  649.         """
  650.         mytimedelta = self._time - _EPOCH
  651.         return _timedeltaToSeconds(mytimedelta)
  652.  
  653.     def asDatetime(self, tzinfo=None):
  654.         """Return this time as an aware datetime.datetime instance.
  655.  
  656.         The returned datetime object has the specified tzinfo, or a tzinfo
  657.         describing UTC if the tzinfo parameter is None.
  658.         """
  659.         if tzinfo is None:
  660.             tzinfo = FixedOffset(0, 0)
  661.  
  662.         if not self.isTimezoneDependent():
  663.             return self._time.replace(tzinfo=tzinfo)
  664.         else:
  665.             return self._time.replace(tzinfo=FixedOffset(0, 0)).astimezone(tzinfo)
  666.  
  667.     def asNaiveDatetime(self, tzinfo=None):
  668.         """Return this time as a naive datetime.datetime instance.
  669.  
  670.         The returned datetime object has its tzinfo set to None, but is in the
  671.         timezone given by the tzinfo parameter, or UTC if the parameter is
  672.         None.
  673.         """
  674.         return self.asDatetime(tzinfo).replace(tzinfo=None)
  675.  
  676.     def asRFC2822(self, tzinfo=None, includeDayOfWeek=True):
  677.         """Return this Time formatted as specified in RFC 2822.
  678.  
  679.         RFC 2822 specifies the format of email messages.
  680.  
  681.         RFC 2822 says times in email addresses should reflect the local
  682.         timezone. If tzinfo is a datetime.tzinfo instance, the returned
  683.         formatted string will reflect that timezone. Otherwise, the timezone
  684.         will be '-0000', which RFC 2822 defines as UTC, but with an unknown
  685.         local timezone.
  686.  
  687.         RFC 2822 states that the weekday is optional. The parameter
  688.         includeDayOfWeek indicates whether or not to include it.
  689.         """
  690.         dtime = self.asDatetime(tzinfo)
  691.  
  692.         if tzinfo is None:
  693.             rfcoffset = '-0000'
  694.         else:
  695.             rfcoffset = '%s%02i%02i' % _timedeltaToSignHrMin(dtime.utcoffset())
  696.  
  697.         rfcstring = ''
  698.         if includeDayOfWeek:
  699.             rfcstring += self.rfc2822Weekdays[dtime.weekday()] + ', '
  700.  
  701.         rfcstring += '%i %s %4i %02i:%02i:%02i %s' % (
  702.             dtime.day,
  703.             self.rfc2822Months[dtime.month - 1],
  704.             dtime.year,
  705.             dtime.hour,
  706.             dtime.minute,
  707.             dtime.second,
  708.             rfcoffset)
  709.  
  710.         return rfcstring
  711.  
  712.     def asISO8601TimeAndDate(self, includeDelimiters=True, tzinfo=None,
  713.                              includeTimezone=True):
  714.         """Return this time formatted as specified by ISO 8861.
  715.  
  716.         ISO 8601 allows optional dashes to delimit dates and colons to delimit
  717.         times. The parameter includeDelimiters (default True) defines the
  718.         inclusion of these delimiters in the output.
  719.  
  720.         If tzinfo is a datetime.tzinfo instance, the output time will be in the
  721.         timezone given. If it is None (the default), then the timezone string
  722.         will not be included in the output, and the time will be in UTC.
  723.  
  724.         The includeTimezone parameter coresponds to the inclusion of an
  725.         explicit timezone. The default is True.
  726.         """
  727.         if not self.isTimezoneDependent():
  728.             tzinfo = None
  729.         dtime = self.asDatetime(tzinfo)
  730.  
  731.         if includeDelimiters:
  732.             dateSep = '-'
  733.             timeSep = ':'
  734.         else:
  735.             dateSep = timeSep = ''
  736.  
  737.         if includeTimezone:
  738.             if tzinfo is None:
  739.                 timezone = '+00%s00' % (timeSep,)
  740.             else:
  741.                 sign, hour, min = _timedeltaToSignHrMin(dtime.utcoffset())
  742.                 timezone = '%s%02i%s%02i' % (sign, hour, timeSep, min)
  743.         else:
  744.             timezone = ''
  745.  
  746.         microsecond = ('%06i' % (dtime.microsecond,)).rstrip('0')
  747.         if microsecond:
  748.             microsecond = '.' + microsecond
  749.  
  750.         parts = [
  751.             ('%04i' % (dtime.year,), datetime.timedelta(days=366)),
  752.             ('%s%02i' % (dateSep, dtime.month), datetime.timedelta(days=31)),
  753.             ('%s%02i' % (dateSep, dtime.day), datetime.timedelta(days=1)),
  754.             ('T', datetime.timedelta(hours=1)),
  755.             ('%02i' % (dtime.hour,), datetime.timedelta(hours=1)),
  756.             ('%s%02i' % (timeSep, dtime.minute), datetime.timedelta(minutes=1)),
  757.             ('%s%02i' % (timeSep, dtime.second), datetime.timedelta(seconds=1)),
  758.             (microsecond, datetime.timedelta(microseconds=1)),
  759.             (timezone, datetime.timedelta(hours=1))
  760.         ]
  761.  
  762.         formatted = ''
  763.         for part, minResolution in parts:
  764.             if self.resolution <= minResolution:
  765.                 formatted += part
  766.  
  767.         return formatted
  768.  
  769.     def asStructTime(self, tzinfo=None):
  770.         """Return this time represented as a time.struct_time.
  771.  
  772.         tzinfo is a datetime.tzinfo instance coresponding to the desired
  773.         timezone of the output. If is is the default None, UTC is assumed.
  774.         """
  775.         dtime = self.asDatetime(tzinfo)
  776.         if tzinfo is None:
  777.             return dtime.utctimetuple()
  778.         else:
  779.             return dtime.timetuple()
  780.  
  781.     def asHumanly(self, tzinfo=None, now=None):
  782.         """Return this time as a short string, tailored to the current time.
  783.  
  784.         Parts of the date that can be assumed are omitted. Consequently, the
  785.         output string depends on the current time. This is the format used for
  786.         displaying dates in most user visible places in the quotient web UI.
  787.  
  788.         By default, the current time is determined by the system clock. The
  789.         current time used for formatting the time can be changed by providing a
  790.         Time instance as the parameter 'now'.
  791.         """
  792.         if now is None:
  793.             now = Time().asDatetime(tzinfo)
  794.         else:
  795.             now = now.asDatetime(tzinfo)
  796.         dtime = self.asDatetime(tzinfo)
  797.  
  798.         # Same day?
  799.         if dtime.date() == now.date():
  800.             if self.isAllDay():
  801.                 return 'all day'
  802.             return dtime.strftime('%I:%M %p').lower()
  803.         else:
  804.             res = str(dtime.date().day) + dtime.strftime(' %b')  # day + month
  805.             # Different year?
  806.             if not dtime.date().year == now.date().year:
  807.                 res += dtime.strftime(' %Y')
  808.             if not self.isAllDay():
  809.                 res += dtime.strftime(', %I:%M %p').lower()
  810.             return res
  811.  
  812.     #
  813.     # methods to return related times
  814.     #
  815.  
  816.     def getBounds(self, tzinfo=None):
  817.         """Return a pair describing the bounds of self.
  818.  
  819.         This returns a pair (min, max) of Time instances. It is not quite the
  820.         same as (self, self + self.resolution). This is because timezones are
  821.         insignificant for instances with a resolution greater or equal to 1
  822.         day.
  823.  
  824.         To illustrate the problem, consider a Time instance:
  825.  
  826.             T = Time.fromHumanly('today', tzinfo=anything)
  827.  
  828.         This will return an equivalent instance independent of the tzinfo used.
  829.         The hour, minute, and second of this instance are 0, and its resolution
  830.         is one day.
  831.  
  832.         Now say we have a sorted list of times, and we want to get all times
  833.         for 'today', where whoever said 'today' is in a timezone that's 5 hours
  834.         ahead of UTC. The start of 'today' in this timezone is UTC 05:00. The
  835.         example instance T above is before this, but obviously it is today.
  836.  
  837.         The min and max times this returns are such that all potentially
  838.         matching instances are within this range. However, this range might
  839.         contain unmatching instances.
  840.  
  841.         As an example of this, if 'today' is April first 2005, then
  842.         Time.fromISO8601TimeAndDate('2005-04-01T00:00:00') sorts in the same
  843.         place as T from above, but is not in the UTC+5 'today'.
  844.  
  845.         TIME IS FUN!
  846.         """
  847.         if self.resolution >= datetime.timedelta(days=1) \
  848.         and tzinfo is not None:
  849.             time = self._time.replace(tzinfo=tzinfo)
  850.         else:
  851.             time = self._time
  852.  
  853.         return (
  854.             min(self.fromDatetime(time), self.fromDatetime(self._time)),
  855.             max(self.fromDatetime(time + self.resolution),
  856.                 self.fromDatetime(self._time + self.resolution))
  857.         )
  858.  
  859.     def oneDay(self):
  860.         """Return a Time instance representing the day of the start of self.
  861.  
  862.         The returned new instance will be set to midnight of the day containing
  863.         the first instant of self in the specified timezone, and have a
  864.         resolution of datetime.timedelta(days=1).
  865.         """
  866.         day = self.__class__.fromDatetime(self.asDatetime().replace(
  867.                 hour=0, minute=0, second=0, microsecond=0))
  868.         day.resolution = datetime.timedelta(days=1)
  869.         return day
  870.  
  871.     #
  872.     # useful predicates
  873.     #
  874.  
  875.     def isAllDay(self):
  876.         """Return True iff this instance represents exactly all day."""
  877.         return self.resolution == datetime.timedelta(days=1)
  878.  
  879.     def isTimezoneDependent(self):
  880.         """Return True iff timezone is relevant for this instance.
  881.  
  882.         Timezone is only relevent for instances with a resolution better than
  883.         one day.
  884.         """
  885.         return self.resolution < datetime.timedelta(days=1)
  886.  
  887.     #
  888.     # other magic methods
  889.     #
  890.  
  891.     def __cmp__(self, other):
  892.         if not isinstance(other, Time):
  893.             raise TypeError("Cannot meaningfully compare %r with %r" % (self, other))
  894.         return cmp(self._time, other._time)
  895.  
  896.     def __eq__(self, other):
  897.         if isinstance(other, Time):
  898.             return cmp(self._time, other._time) == 0
  899.         return False
  900.  
  901.     def __ne__(self, other):
  902.         return not (self == other)
  903.  
  904.     def __repr__(self):
  905.         return 'extime.Time.fromDatetime(%r)' % (self._time,)
  906.  
  907.     __str__ = asISO8601TimeAndDate
  908.  
  909.     def __contains__(self, other):
  910.         """Test if another Time instance is entirely within the period addressed by this one."""
  911.         if not isinstance(other, Time):
  912.             raise TypeError(
  913.                 '%r is not a Time instance; can not test for containment'
  914.                 % (other,))
  915.         if other._time < self._time:
  916.             return False
  917.         if self._time + self.resolution < other._time + other.resolution:
  918.             return False
  919.         return True
  920.  
  921.     def __add__(self, addend):
  922.         if not isinstance(addend, datetime.timedelta):
  923.             raise TypeError, 'expected a datetime.timedelta instance'
  924.         return Time.fromDatetime(self._time + addend)
  925.  
  926.     def __sub__(self, subtrahend):
  927.         """
  928.         Implement subtraction of an interval or another time from this one.
  929.  
  930.         @type subtrahend: L{datetime.timedelta} or L{Time}
  931.  
  932.         @param subtrahend: The object to be subtracted from this one.
  933.  
  934.         @rtype: L{datetime.timedelta} or L{Time}
  935.  
  936.         @return: If C{subtrahend} is a L{datetime.timedelta}, the result is
  937.         a L{Time} instance which is offset from this one by that amount.  If
  938.         C{subtrahend} is a L{Time}, the result is a L{datetime.timedelta}
  939.         instance which gives the difference between it and this L{Time}
  940.         instance.
  941.         """
  942.         if isinstance(subtrahend, datetime.timedelta):
  943.             return Time.fromDatetime(self._time - subtrahend)
  944.  
  945.         if isinstance(subtrahend, Time):
  946.             return self.asDatetime() - subtrahend.asDatetime()
  947.  
  948.         return NotImplemented
  949.